package com.intelligentmeterreadingsys.waterlist.activity;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.AlertDialog.Builder;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.ContentValues;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

import com.intelligentmeterreadingsys.R;
import com.intelligentmeterreadingsys.httpserver.HttpClientServer;
import com.intelligentmeterreadingsys.httpserver.HttpDownload;
import com.intelligentmeterreadingsys.httpserver.RequestUrl;
import com.intelligentmeterreadingsys.povo.NavigationPoVo;
import com.intelligentmeterreadingsys.util.FileNameUtil;
import com.intelligentmeterreadingsys.util.SharedPreferenceUtil;
import com.intelligentmeterreadingsys.waterlist.copywater.activity.CopyWaterListActivity;
import com.intelligentmeterreadingsys.waterlist.copywater.activity.CopyWaterRFIDActivity;
import com.intelligentmeterreadingsys.waterlist.copywater.db.CopyWaterDao;
import com.intelligentmeterreadingsys.waterlist.db.WaterListDaoImpl;
import com.intelligentmeterreadingsys.waterlist.querywaterlist.activity.QueryWaterListActivity;
import com.intelligentmeterreadingsys.waterlist.querywaterlist.activity.RadioReportActivity;

import dbhelper.DbTableName;
import dbhelper.XmlNameHelper;

/**
 * 表册管理
 * 
 * @author king
 * 
 */
public class WaterListMainActivity extends Activity implements OnClickListener {

    public Button button1;// 抄表

    public Button button2;// 表册查询

    public Button button3;// 无线上报

    public Button button4;// 任务单

    public Button button5;// 抄表数据复查

    public int watertotal = 0;

    public WaterListDaoImpl dao = null;

    public SharedPreferenceUtil sp = null;

    public final static int DIALOG = 1;

    public boolean isSafe = false;

    public ProgressDialog pd;

    public RequestUrl r;

    int total = 0;

    public String downtype = "我想重新下载表册";

    public long time;
    public List<NavigationPoVo> listNaInfo;

    public FileNameUtil fi;

    public WaterListDaoImpl daos;

    public String[] date = new String[] { "我想重新下载表册", "只想下载导航数据" };

    @Override
    protected void onCreate(Bundle savedInstanceState) {

	super.onCreate(savedInstanceState);
	setContentView(R.layout.waterlistmain);
	inti();

    }

    /**
     * 初始化控件并注册点击监听事件
     */

    public void inti() {
	sp = new SharedPreferenceUtil(this);
	r = new RequestUrl(this);
	fi = new FileNameUtil(this);
	daos = new WaterListDaoImpl(this);
	isSafe = sp.getBoolean(XmlNameHelper.isSafe);
	button1 = (Button) findViewById(R.id.writewater);
	button2 = (Button) findViewById(R.id.querywaterlist);
	button3 = (Button) findViewById(R.id.wirelessupload);
	button4 = (Button) findViewById(R.id.tasklist);

	button1.setOnClickListener(this);
	button2.setOnClickListener(this);
	button3.setOnClickListener(this);
	button4.setOnClickListener(this);

    }

    /**
     * 添加点击事件
     */
    @Override
    public void onClick(View v) {
	Intent intent = null;
	switch (v.getId()) {
	case R.id.writewater:
	    SharedPreferenceUtil sh = new SharedPreferenceUtil(WaterListMainActivity.this);
	    isSafe = sh.getBoolean(XmlNameHelper.isSafe);
	    if (isSafe) {
		CopyWaterDao dao = new CopyWaterDao(this);
		if (dao.queryAllWaterList().size() > 1) {
		    intent = new Intent(WaterListMainActivity.this, CopyWaterListActivity.class);
		} else {
		    intent = new Intent(WaterListMainActivity.this, CopyWaterRFIDActivity.class);
		}
		dao.close();
		startActivity(intent);
	    } else {
		showDialog(CopyWaterListActivity.class);
	    }

	    break;
	case R.id.querywaterlist:
	    intent = new Intent(this, QueryWaterListActivity.class);
	    startActivity(intent);
	    break;
	case R.id.wirelessupload:
	    intent = new Intent(this, RadioReportActivity.class);
	    startActivity(intent);
	    break;
	case R.id.tasklist:
	    WaterListDaoImpl dao = new WaterListDaoImpl(this);
	    int number = dao.queryNoUpload();
	    int townumber = dao.queryTowCopy();
	    boolean b = dao.isWaterList();
	    dao.close();
	    if (b) {
		showDialog(DIALOG + 3);
		return;
	    }
	    if (number > 0) {
		Toast.makeText(WaterListMainActivity.this, "你还有没上的表册，不能下载", Toast.LENGTH_LONG).show();
		return;
	    }
	    if (townumber > 0) {
		showDialog(DIALOG);
	    } else {
		showDialog(DIALOG + 1);
	    }

	    break;

	default:
	    break;
	}

    }

    public class download extends AsyncTask<String, Integer, String> {

	public HttpClientServer server;

	public ProgressDialog dialog;

	public download(ProgressDialog dialog) {
	    this.dialog = dialog;
	}

	@Override
	protected String doInBackground(String... params) {

	    String userid = sp.getValue(XmlNameHelper.IMSI);

	    Map<String, String> map = new HashMap<String, String>();
	    map.put("imsi", userid);
	    String response = server.doPost(map, params[0]);

	    if (!response.equals("error")) {
		try {
		    JSONObject obj = new JSONObject(response);
		    // 水表信息
		    JSONArray waterinfo = obj.getJSONArray("waterinfo");

		    int a = watertotal = waterinfo.length();
		    // 表册信息
		    JSONArray waterlist = obj.getJSONArray("tlps");
		    int b = waterlist.length();
		    // 用户信息
		    JSONArray userinfo = obj.getJSONArray("userinfo");
		    int c = userinfo.length();
		    // 月用水量信息
		    JSONArray usewater = obj.getJSONArray("usewaterinfo");
		    // 工程单类型
		    JSONArray ordertype = obj.getJSONArray("typeinfo");

		    int d = usewater.length();
		    total = a + b + c + d;

		    List<ContentValues> listwaterinfo = new ArrayList<ContentValues>();
		    List<ContentValues> daohanginof = new ArrayList<ContentValues>();
		    if (waterinfo != null && waterinfo.length() > 0) {
			for (int i = 0; i < waterinfo.length(); i++) {
			    JSONObject jb = waterinfo.getJSONObject(i);
			    ContentValues value = new ContentValues();

			    value.put("waternumber", jb.getString("waternumber"));
			    String waternumber = jb.getString("waternumber");
			    value.put("waterlistid", jb.getString("waterlistid"));
			    value.put("usernumber", jb.getString("usernumber"));
			    value.put("wateradds", jb.getString("wateradds"));
			    value.put("groupwatersort", jb.getInt("meterIndex"));

			    value.put("groupingsort", jb.getInt("arrayIndex"));

			    value.put("groupingname", jb.getString("arrayName"));

			    System.out.println("组名" + jb.getString("arrayName"));
			    if (jb.getString("alarmlimit").equals("null")) {
				value.put("alarmlimit", 0.0);
			    } else {
				value.put("alarmlimit", jb.getDouble("alarmlimit"));
			    }

			    if (jb.getString("lowalarmlimit").equals("null")) {
				value.put("lowalarmlimit", 0.0);
			    } else {
				value.put("lowalarmlimit", jb.getDouble("lowalarmlimit"));
			    }

			    String latitude = jb.getString("latitude");
			    String rfidnumber = jb.getString("RFIDnumber");
			    if (!rfidnumber.equals("null")) {
				value.put("RFIDnumber", jb.getString("RFIDnumber"));
			    }
			    if (rfidnumber.equals("null") && latitude.equals("null")) {
				value.put("bandingstatus", "2");
			    } else {
				value.put("bandingstatus", "3");
			    }

			    if (!latitude.equals("null")) {
				value.put("latitude", jb.getDouble("latitude"));
			    }
			    String longitude = jb.getString("longitude");
			    if (!longitude.equals("null")) {
				value.put("longitude", jb.getDouble("longitude"));
			    }
			    String lastmonthwater = jb.getString("lastmonthwater");

			    if (!lastmonthwater.equals("null")) {

				value.put("lastmonthwater", jb.getDouble("lastmonthwater"));
			    } else {
				value.put("lastmonthwater", 0.0);
			    }

			    value.put("metercaliber", jb.getString("metercaliber"));
			    if (jb.getString("lastdate").equals("null")) {
				value.put("lastdate", "第一次抄");
			    } else {
				value.put("lastdate", jb.getString("lastdate"));
			    }

			    value.put("iscopystatus", "未抄");
			    value.put("isupload", "0");
			    value.put("ismultiplecopy", "0");
			    value.put("waterproperties", jb.getString("waterproperties"));
			    value.put("adds", jb.getString("addr"));

			    JSONArray json = jb.getJSONArray("imvs");
			    if (json != null && json.length() > 0) {
				value.put("Navigationdownload", "0");
				for (int n = 0; n < json.length(); n++) {
				    JSONObject j = json.getJSONObject(n);
				    ContentValues values = new ContentValues();
				    values.put("othernumber", waternumber);

				    values.put("imgwebname", j.getString("text"));
				    System.out.println("text" + j.getString("text"));
				    values.put("Sortnumber", j.getInt("index"));
				    values.put("isimg", j.getString("type"));
				    if (j.getString("type").equals("1")) {
					values.put("isdownload", "0");
				    } else {
					values.put("imgpath", j.getString("text"));
					values.put("isdownload", "1");
				    }
				    values.put("type", "1");
				    daohanginof.add(values);
				}

			    }
			    listwaterinfo.add(value);
			    publishProgress(i + 1);

			}

		    }

		    List<ContentValues> listuserinfo = new ArrayList<ContentValues>();
		    if (userinfo != null && userinfo.length() > 0) {
			for (int i = 0; i < userinfo.length(); i++) {
			    JSONObject jb = userinfo.getJSONObject(i);
			    ContentValues value = new ContentValues();
			    value.put("username", jb.getString("name"));
			    value.put("usernumber", jb.getString("number"));
			    value.put("phone", jb.getString("phone"));
			    value.put("useradds", jb.getString("adds"));
			    value.put("usertype", jb.getString("usertype"));
			    value.put("userstatus", jb.getString("status"));
			    value.put("ismultiplecopy", "0");
			    listuserinfo.add(value);
			    publishProgress(a + i + 1);
			}
		    }

		    List<ContentValues> listusewater = new ArrayList<ContentValues>();
		    if (usewater != null && usewater.length() > 0) {
			for (int i = 0; i < usewater.length(); i++) {
			    JSONObject js = usewater.getJSONObject(i);
			    ContentValues value = new ContentValues();
			    value.put("waternumber", js.getString("waternumber"));
			    value.put("month", js.getString("month"));
			    if (js.getString("watercount").equals("null")) {
				value.put("watercount", 0);
			    } else {
				value.put("watercount", js.getString("watercount"));
			    }
			    value.put("ismultiplecopy", "0");
			    listusewater.add(value);
			    publishProgress(a + c + i + 1);
			}
		    }

		    List<ContentValues> listwaterlist = new ArrayList<ContentValues>();
		    if (waterlist != null && waterlist.length() > 0) {
			for (int i = 0; i < waterlist.length(); i++) {
			    JSONObject js = waterlist.getJSONObject(i);
			    ContentValues value = new ContentValues();
			    value.put("number", js.getString("tbl_id"));
			    value.put("name", js.getString("tbl_name"));

			    listwaterlist.add(value);
			    publishProgress(a + b + c + i + 1);

			}
		    }

		    List<ContentValues> listordertype = new ArrayList<ContentValues>();
		    if (ordertype != null && ordertype.length() > 0) {
			for (int i = 0; i < ordertype.length(); i++) {
			    JSONObject json = ordertype.getJSONObject(i);
			    ContentValues value = new ContentValues();
			    value.put("name", json.getString("name"));
			    value.put("number", json.getString("number"));
			    value.put("status", "2");
			    listordertype.add(value);
			}
		    }

		    dao.insertALL(listordertype, DbTableName.TYPE);
		    boolean b1 = false;
		    b1 = dao.insertALL(listwaterlist, DbTableName.WATERLIST);
		    if (b1) {
			b1 = dao.insertALL(listuserinfo, DbTableName.USERINFO);
			if (b1) {
			    b1 = dao.insertALL(listusewater, DbTableName.USEWATERINFO);
			    if (b1) {
				b1 = dao.insertALL(listwaterinfo, DbTableName.WATERINFO);

				b1 = dao.insertALL(daohanginof, DbTableName.NAVIGATION);

			    }
			}
		    }

		    dao.close();
		    if (b1) {

			return "success";
		    } else {

			return "error";
		    }
		} catch (JSONException e) {
		    dao.close();
		    System.out.println(e);
		    e.printStackTrace();

		}

	    }
	    return "error";

	}

	@Override
	protected void onPreExecute() {
	    server = new HttpClientServer(WaterListMainActivity.this);
	    dao = new WaterListDaoImpl(WaterListMainActivity.this);

	    dialog.setMax(100);
	    dialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
	    dialog.setTitle("下载数据中.......");
	    dialog.setCancelable(false);
	    dialog.show();

	}

	@Override
	protected void onProgressUpdate(Integer... values) {

	    dialog.setProgress((int) ((float) total / 100 * values[0]));
	}

	@Override
	protected void onPostExecute(String result) {

	    dialog.cancel();
	    if (TextUtils.isEmpty(result)) {
		Toast.makeText(WaterListMainActivity.this, "下载失败", Toast.LENGTH_SHORT).show();
	    } else if (result.equals("error")) {
		Toast.makeText(WaterListMainActivity.this, "网络连接失败", Toast.LENGTH_SHORT).show();
	    } else {
		Toast.makeText(WaterListMainActivity.this, "下载成功,共下载抄表数据:" + watertotal, Toast.LENGTH_SHORT).show();
		boolean b = daos.modifyAlarm();
		System.out.println(b + "修改报警上下限");
		int k = daos.queryNavigationTotal();
		listNaInfo = daos.queryNavigtionImgTotal();
		if (k > 0) {

		    showDialog(DIALOG + 2);
		}
	    }

	}

    }

    @Override
    protected Dialog onCreateDialog(int id) {
	Dialog dialog = null;
	switch (id) {
	case DIALOG:
	    Builder builder = new android.app.AlertDialog.Builder(this);
	    // 设置对话框的图标
	    builder.setIcon(R.drawable.buttondraw);
	    // 设置对话框的标题
	    builder.setMessage("你有标注的二次抄表哟！确定将下载新的表册！");

	    // 添加一个确定按钮
	    builder.setPositiveButton(" 确 定 ", new DialogInterface.OnClickListener() {
		public void onClick(DialogInterface dialog, int which) {

		    dao = new WaterListDaoImpl(WaterListMainActivity.this);
		    dao.delectWaterList();
		    dao.delectNavigation();
		    dao.close();
		    FileNameUtil fi = new FileNameUtil(WaterListMainActivity.this);
		    fi.delectFile("waterimage");
		    ProgressDialog pd = new ProgressDialog(WaterListMainActivity.this);

		    download d = new download(pd);
		    d.execute(RequestUrl.DownloadWaterList);
		}
	    });

	    builder.setNeutralButton("取消", new android.content.DialogInterface.OnClickListener() {

		@Override
		public void onClick(DialogInterface dialog, int which) {

		}
	    });
	    // 创建一个单选按钮对话框
	    dialog = builder.create();
	    break;
	case DIALOG + 1:
	    Builder builder1 = new android.app.AlertDialog.Builder(this);
	    // 设置对话框的图标
	    builder1.setIcon(R.drawable.buttondraw);
	    builder1.setMessage("确定下载新表册？");
	    builder1.setPositiveButton("确定", new android.content.DialogInterface.OnClickListener() {

		@Override
		public void onClick(DialogInterface dialog, int which) {

		    dao = new WaterListDaoImpl(WaterListMainActivity.this);
		    dao.delectWaterList();
		    dao.delectNavigation();
		    dao.close();
		    FileNameUtil fi = new FileNameUtil(WaterListMainActivity.this);
		    fi.delectFile("waterimage");
		    ProgressDialog pd = new ProgressDialog(WaterListMainActivity.this);

		    download d = new download(pd);
		    d.execute(RequestUrl.DownloadWaterList);

		}
	    });
	    builder1.setNeutralButton("取消", new android.content.DialogInterface.OnClickListener() {

		@Override
		public void onClick(DialogInterface dialog, int which) {

		}
	    });
	    // 创建一个单选按钮对话框
	    dialog = builder1.create();
	    break;

	case DIALOG + 2:
	    builder1 = new android.app.AlertDialog.Builder(this);
	    // 设置对话框的图标
	    builder1.setIcon(R.drawable.buttondraw);
	    builder1.setMessage("即将开始下载图文导航，建议在WIFI下下载");
	    builder1.setPositiveButton("确定", new android.content.DialogInterface.OnClickListener() {

		@Override
		public void onClick(DialogInterface dialog, int which) {

		    final FileNameUtil fi = new FileNameUtil(WaterListMainActivity.this);
		    fi.delectFile("DaoHang");
		    pd = new ProgressDialog(WaterListMainActivity.this);

		    pd.setMax(listNaInfo.size());
		    pd.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
		    pd.setTitle("下载数据中.......");
		    time = System.currentTimeMillis();
		    pd.setCancelable(false);
		    if (dao != null) {
			dao.close();
		    }

		    pd.show();
		    isSafe = true;
		    new Thread() {

			@Override
			public void run() {
			    for (int i = 0; i < listNaInfo.size(); i++) {
				if (!isSafe) {
				    return;
				}

				NavigationPoVo na = listNaInfo.get(i);
				String url = r.getUrl("/" + na.getWebdesc());
				HttpDownload down = new HttpDownload();
				String[] s = na.getWebdesc().split("/");

				String fileName = s[s.length - 1];

				fi.SDCardPath("DaoHang/" + na.getOtherid());
				String path = fi.getSDPath() + "/DownFile/DaoHang/" + na.getOtherid() + "/" + fileName;
				int k = 0;
				k = down.DownImage(url, fi.getSDPath() + "/DownFile/DaoHang/" + na.getOtherid(), fileName);

				System.out.println("下载状态" + k);
				if (k == 0) {
				    System.out.println(path + "-------------");
				    daos.modifyNavigation(na.getId(), path);
				    Message msg = myHandler.obtainMessage();
				    msg.what = k;
				    msg.arg1 = i;
				    myHandler.sendMessage(msg);
				} else {
				    Message msg = myHandler.obtainMessage();
				    msg.what = 1;

				    myHandler.sendMessage(msg);
				}

			    }
			    super.run();
			}

		    }.start();
		}
	    });
	    builder1.setNeutralButton("取消", new android.content.DialogInterface.OnClickListener() {

		@Override
		public void onClick(DialogInterface dialog, int which) {

		}
	    });
	    // 创建一个单选按钮对话框
	    dialog = builder1.create();
	    break;
	case DIALOG + 3:
	    date = new String[] { "我想重新下载表册", "只想下载导航数据" };
	    Builder builder2 = new android.app.AlertDialog.Builder(this);
	    // 设置对话框的图标
	    builder2.setIcon(R.drawable.buttondraw);
	    builder2.setTitle("请选择");
	    builder2.setSingleChoiceItems(date, 0, new android.content.DialogInterface.OnClickListener() {
		public void onClick(DialogInterface dialog, int which) {
		    downtype = date[which];

		}
	    });
	    builder2.setPositiveButton("确定", new android.content.DialogInterface.OnClickListener() {

		@Override
		public void onClick(DialogInterface dialog, int which) {
		    if (downtype.equals("我想重新下载表册")) {
			dao = new WaterListDaoImpl(WaterListMainActivity.this);
			dao.delectWaterList();
			dao.delectNavigation();
			dao.close();
			FileNameUtil fi = new FileNameUtil(WaterListMainActivity.this);
			fi.delectFile("waterimage");
			fi.delectFile("DaoHang");
			ProgressDialog pd = new ProgressDialog(WaterListMainActivity.this);

			download d = new download(pd);
			d.execute(RequestUrl.DownloadWaterList);
		    } else {
			downNa();

		    }

		}
	    });
	    builder2.setNeutralButton("取消", new android.content.DialogInterface.OnClickListener() {

		@Override
		public void onClick(DialogInterface dialog, int which) {

		}
	    });
	    // 创建一个单选按钮对话框
	    dialog = builder2.create();
	    break;
	}

	return dialog;
    }

    public boolean showDialog(final Class<?> activityClass) {

	LayoutInflater factory = LayoutInflater.from(this);
	final View textEntryView = factory.inflate(R.layout.dialog, null);
	final EditText editTextPass = (EditText) textEntryView.findViewById(R.id.txt_password);

	AlertDialog.Builder ad1 = new AlertDialog.Builder(this);
	ad1.setIcon(android.R.drawable.ic_dialog_info);
	ad1.setView(textEntryView);
	ad1.setTitle("安全验证");
	ad1.setPositiveButton("确定", new android.content.DialogInterface.OnClickListener() {

	    @Override
	    public void onClick(DialogInterface dialog, int which) {
		String pass = editTextPass.getEditableText().toString();
		SharedPreferenceUtil sh = new SharedPreferenceUtil(WaterListMainActivity.this);
		if (pass.equals(sh.getValue(XmlNameHelper.passWord))) {
		    isSafe = true;
		    Intent intents = new Intent(WaterListMainActivity.this, activityClass);
		    startActivity(intents);

		} else {
		    Toast.makeText(WaterListMainActivity.this, "密码错误", 1000).show();
		    isSafe = false;
		}

	    }
	});
	ad1.setNegativeButton("取消", new android.content.DialogInterface.OnClickListener() {

	    @Override
	    public void onClick(DialogInterface dialog, int which) {
		isSafe = false;

	    }
	});
	ad1.create();
	ad1.show();
	return isSafe;

    }

    // 下载图文消息处理
    Handler myHandler = new Handler() {

	@Override
	public void handleMessage(Message msg) {
	    if (msg.what == 0) {
		pd.setProgress(msg.arg1 + 1);
	    } else if (msg.what == 1) {
		Toast.makeText(WaterListMainActivity.this, "下载失败", Toast.LENGTH_SHORT).show();
		isSafe = false;
		pd.dismiss();

	    }
	    if (listNaInfo.size() == msg.arg1 + 1) {

		fi.delectFile("DownFile/DaoHang");
		fi.delectFile("DownFile");
		Toast.makeText(WaterListMainActivity.this, "导航数据下载完成", Toast.LENGTH_SHORT).show();
		pd.dismiss();

	    }
	    super.handleMessage(msg);
	}

    };

    @Override
    protected void onDestroy() {
	daos.close();
	super.onDestroy();
    }

    // 下载导航数据
    public void downNa() {
	int k = daos.queryNavigationTotal();
	listNaInfo = daos.queryNavigtionImgTotal();
	if (k > 0) {
	    showDialog(DIALOG + 2);
	} else {
	    Toast.makeText(this, "没有可下载的导航数据", Toast.LENGTH_SHORT).show();
	}
    }
}
